package com.medical.blood.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.medical.blood.annotation.LogOperation;
import com.medical.blood.entity.OperationLog;
import com.medical.blood.mapper.OperationLogMapper;
import com.medical.blood.annotation.LogOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Around("@annotation(com.medical.blood.annotation.LogOperation)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            LogOperation logAnnotation = method.getAnnotation(LogOperation.class);

            OperationLog operationLog = new OperationLog();
            // 设置操作IP
            operationLog.setOperationIp(request.getRemoteAddr());
            // 设置操作时间
            operationLog.setOperationTime(new Date());
            // 设置操作类型
            operationLog.setOperationType(logAnnotation.operationType());
            // 简单处理描述，可根据实际需求完善
            operationLog.setOperationContent(logAnnotation.description());

            // 这里需要根据实际业务获取operatorType和operatorId，示例中简单设置
            operationLog.setOperatorType(1);
            operationLog.setOperatorId(1L);

            // 保存日志到数据库
            operationLogMapper.insert(operationLog);
        }
        return result;
    }
}